
var ProfileController = function($scope, $http){
	$http.defaults.headers.post["Content-Type"] = "application/json";
	var urlBase="http://localhost:8080/finalproject";
	
	$scope.dataUrls = [];
	
	$scope.getUserProfile = function(){
		$scope.resetError();
		$http.get(urlBase + '/profile/user').success(function(respone){
			$scope.am = respone;
		}).error(function(){
			$scope.setError("Can't get user profile");
		});
	}
	
	 $scope.onFileSelect = function($files){
    	 var $file = $files[0];
         if(window.FileReader && $file.type.indexOf('image') > -1){
                 var fileReader = new FileReader();
                 fileReader.readAsDataURL($file);
                 
                 fileReader.onload = function(e){
                         $scope.dataUrls['imagenew'] = e.target.result;
                 }
         }
         
         $scope.upload = $upload.upload({
                 url: urlBase + '/profile/file/upload',
         }).progress(function(evt){
                 $scope.percent = parseInt(100.0 * evt.loaded / evt.total);
                  console.log('percent: ' +  $scope.percent);
         }).success(function(respone){
        	 console.log($scope.dataUrls['imagenew']);
        	 	$scope.sendToDatabase($scope.dataUrls['imagenew']);
                 console.log("upload finished");
         }).error(function(){
                 console.log("upload failed");
         });
         
         
     };
     
     $scope.sendToDatabase = function(dataUrlsN){
         $http.post(urlBase + '/profile/file/image', dataUrlsN).success(function(respone){
                 $scope.dataUrls['image'] = respone;
         }).error(function(){
                 alert("failed");
         })
     }
     
     $scope.updateUser = function(am){
    	 $scope.resetError();
    	 if(typeof $scope.password == 'undefined'){
    		 $http.post(urlBase + '/profile/passwordold/updateuser', am).success(function(respone){
    			 $scope.getUserProfile();
    			 $scope.setError("Update user successfully");
    		 }).error(function(respone){
    			 $scope.setError("Can't update user");
    		 });
    	 } else {
    		 am.password = $scope.password;
    		 $http.post(urlBase + '/profile/passwordnew/updateuser', am).success(function(respone){
    			 $scope.getUserProfile();
    			 $scope.setError("Update user successfully");
    		 }).error(function(respone){
    			 $scope.setError("Can't update user");
    		 });
    	 }
     }
	
	 $scope.setError = function(message){
         $scope.error = true;
         $scope.errorMessage = message;
	 }
	 
	 $scope.resetError = function(){
	         $scope.error = false;
	         $scope.errorMessage = '';
	 }
		
	$scope.getUserProfile();
}